/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */

package org.jaxson.struts.encoder;


import java.io.Serializable;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;


/**
 * Class for serializing beans to XML.
 * 
 * @author Joe Maisel
 */
public class XmlEncoder extends ResponseEncoder
{
	private String dtd;
	private String schema;
	
	public void setDTD(String dtd){
		this.dtd = dtd;
	}
	
	public String getDTD(){
		return this.dtd;
	}
	
	public String getSchema() {
		return schema;
	}

	public void setSchema(String schema) {
		this.schema = schema;
	}

	/**
	 * @throws EncodingException
	 * @see org.jaxson.struts.ResponseEncoder#encode(java.io.Serializable)
	 */
	@Override
	public void encode( Serializable model ) throws EncodingException
	{
		try
		{
			XStream xstream = new XStream( new DomDriver() );
			StringBuffer xml = new StringBuffer(xstream.toXML( model ));
			
			write( "<?xml version=\"1.0\"?>\n".getBytes() );
			
			if( dtd != null ){
				write( (dtd + "\n").getBytes() );
			}
			
			if( schema != null ){
				xml.insert(xml.indexOf(">"), " " + schema);
			}
			
			write( xml.toString().getBytes() );
		}
		catch( Exception e )
		{
			e.printStackTrace();
			throw new EncodingException();
		}
	}

}
